package com.elight.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtils {
	/// <summary>
	/// 导出Excel
	/// </summary>
	/// <typeparam name="T"></typeparam>
	/// <param name="data"></param>
	/// <param name="headDict"></param>
	/// <param name="sheetName"></param>
	/// <returns></returns>
	public static <T> XSSFWorkbook exportExcel(List<T> data, Map<String, String> headMap, String sheetName,
			boolean showSrNo)
			throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		XSSFWorkbook wb = new XSSFWorkbook();
		if (StringUtils.isNullOrEmpty(sheetName)) {
			sheetName = "sheet1";
		}
		XSSFSheet sheet = wb.createSheet(sheetName);
		XSSFRow row = sheet.createRow((int) 0);
		XSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HorizontalAlignment.CENTER);

		List<String> headList = new ArrayList<String>();
		if (showSrNo) {
			headList.add("RowNum");
		}
		for (Entry<String, String> entry : headMap.entrySet()) {
			headList.add(entry.getKey());
		}
		// 添加头部
		for (int i = 0; i < headList.size(); i++) {
			XSSFCell cell = row.createCell(i);
			if (showSrNo && headList.get(i).equals("RowNum")) {
				cell.setCellValue("序号");
			} else {
				cell.setCellValue(headMap.get(headList.get(i)));
			}
			cell.setCellStyle(style);
			sheet.autoSizeColumn(i);
		}
		// 循环添加内容
		for (int i = 0; i < data.size(); i++) {
			T entity = data.get(i);
			row = sheet.createRow(i + 1);
			for (int j = 0; j < headList.size(); j++) {
				XSSFCell cell = row.createCell(j);
				if (showSrNo && headList.get(j).equals("RowNum")) {
					cell.setCellValue(i);
				} else {
					Method met = entity.getClass().getMethod("get" + initStr(headList.get(j)));
					Object value = met.invoke(entity);
					if (value instanceof Boolean)
						cell.setCellValue((Boolean) value);
					else if (value instanceof Calendar)
						cell.setCellValue((Calendar) value);
					else if (value instanceof Date)
						cell.setCellValue((Date) value);
					else if (value instanceof Double)
						cell.setCellValue((Double) value);
					else if (value instanceof String)
						cell.setCellValue((String) value);
					else
						cell.setCellValue(value.toString());
				}
				cell.setCellStyle(style);
				sheet.autoSizeColumn(j);
			}
		}
		return wb;
	}

	public static String initStr(String old) { // 将单词的首字母大写
		String str = old.substring(0, 1).toUpperCase() + old.substring(1);
		return str;
	}
}
